package cn.school.mybatis.servlet;

import cn.school.mybatis.pojo.Admin;
import cn.school.mybatis.service.AdminService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/doAdminLoginServlet")
public class doAdminLoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        //获取登录页面的属性
        req.setCharacterEncoding("utf-8");
        HttpSession sess=req.getSession();
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String autoLogin = req.getParameter("autoLogin");
        //判断账号密码是否正确
        Admin checkAdmin = AdminService.ADMIN_SERVICE.getUser(username, password);
        if (checkAdmin != null) {
            if (autoLogin != null && !autoLogin.equals("null")) {
                //如果勾选了“记录密码”，把账号密码存到客户端Cookie中
                Cookie c1 = new Cookie("username", username);
                Cookie c2 = new Cookie("password", password);
                c1.setMaxAge(60 * 60 * 24 * 30);
                c2.setMaxAge(60 * 60 * 24 * 30);
                resp.addCookie(c1);
                resp.addCookie(c2);
            } else {//如何不勾选“记录密码”则把客户端的Cookie替换掉，并设置生存周期为0
                Cookie c1 = new Cookie("username", username);
                Cookie c2 = new Cookie("password", null);
                c1.setMaxAge(60 * 60 * 24 * 30);
                c2.setMaxAge(0);
                resp.addCookie(c1);
                resp.addCookie(c2);
            }
            sess.setAttribute("USER_LOGIN", checkAdmin);
            req.getSession().setAttribute("username", username);
            out.println("<script>alert('" + checkAdmin.getUsername() + "欢迎登录！');location.replace('" + req.getContextPath() + "/doLoginWelcomeServlet')</script>");
        } else {
            out.println("<script>location.replace('" + req.getContextPath() + "/WEB-INF/AdminLTEdemo01/s_login/loginFail.jsp')</script>");
        }
    }
}
